package service;

import com.alibaba.fastjson.JSON;
import mapper.StudentMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pojos.common.ReplyMessage;
import pojos.student.OrderSubjectInfo;
import pojos.student.OrderSubjectManager;
import pojos.student.StudentInfo;
import pojos.subject.ClassInfoManager;
import pojos.subject.UserRelationshipManager;
import utils.Md5Utils;
import utils.SpecialCodeReplaceUtil;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.List;

/**
 * 学生服务接口类
 */
public class StudentInfoService {
    private final Logger logger = LoggerFactory.getLogger(StudentInfoService.class);

    @Resource(name = "studentMapper")
    private StudentMapper studentMapper;

    /**
     * 查询所有学生基本信息
     */
    public List<StudentInfo> queryAllStudentBaseInfo(){
        try {
            return studentMapper.queryAllStudentBaseInfo();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询所有学生基本信息出错！");
            return null;
        }
    }

    /**
     * 管理员添加学生
     */
    public ReplyMessage adminAddStudent(StudentInfo studentInfo){
        ReplyMessage replyMessage = new ReplyMessage();

        try {
            // 查询登录名是否被占用
            String nameRe = SpecialCodeReplaceUtil.doReplace(studentInfo.getName());
            Integer isExist = studentMapper.isLoginNameExist(nameRe);
            if(isExist != null && isExist > 0){
                replyMessage.setStatus(400);
                replyMessage.setInfo("登录名已经被使用，请重新更换用户名！");
                return replyMessage;
            }

            // 密码加密
            String passwordEn = Md5Utils.getMd5(studentInfo.getPassword());
            studentInfo.setPassword(passwordEn);
            studentInfo.setName(nameRe);
            studentInfo.setJoinTime(new Timestamp(System.currentTimeMillis()));
            studentMapper.addStudent(studentInfo);
            replyMessage.setStatus(200);
            return replyMessage;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("添加学生信息异常，学生登录名："+studentInfo.getName()+"，登录密码："+studentInfo.getPassword());

            replyMessage.setStatus(500);
            replyMessage.setInfo("服务器异常，请稍后重试！");
            return replyMessage;
        }
    }

    /**
     * 查询所有的学生姓名
     */
    public ReplyMessage queryAllStudentsName(){
        ReplyMessage replyMessage = new ReplyMessage();
        try {
            List<StudentInfo> studentInfoList = studentMapper.queryAllStudentsName();
            if(studentInfoList != null){
                replyMessage.setStatus(200);
                replyMessage.setInfo(JSON.toJSONString(studentInfoList));
                return replyMessage;
            }
            replyMessage.setStatus(400);
            replyMessage.setInfo("查询结果为空！");
            return replyMessage;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询所有学生姓名异常！");

            replyMessage.setStatus(500);
            replyMessage.setInfo("服务器异常！");
            return replyMessage;
        }
    }

    /**
     * 查询所有学生预订课程信息
     */
    public List<OrderSubjectManager> queryAllStudentOrderSubjectInfo(){
        try {
            return studentMapper.queryStudentOrderSubjectInfo();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询学生预订课程信息异常！");

            return null;
        }
    }

    /**
     * 添加学生订购的课程信息
     */
    public ReplyMessage addStudentOrderClass(OrderSubjectInfo subjectInfo){
        subjectInfo.setOrderTime(new Timestamp(System.currentTimeMillis()));

        ReplyMessage replyMessage = new ReplyMessage();
        try {
            studentMapper.addStudentOrderSubject(subjectInfo);

            int idKey = subjectInfo.getId();
            UserRelationshipManager manager = new UserRelationshipManager();
            manager.setOrderId(idKey);
            studentMapper.addStudentRelationship(manager);

            replyMessage.setStatus(200);
            return replyMessage;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("添加学生预订课程异常，学生ID："+subjectInfo.getStudentId()+"，课程ID："+subjectInfo.getSubjectId());

            replyMessage.setStatus(500);
            replyMessage.setInfo("服务器异常，请稍后重试！");
            return replyMessage;
        }
    }

    /**
     * 学生登录检查
     */
    public ReplyMessage studentLoginCheck(String userName, String password){
        ReplyMessage replyMessage = new ReplyMessage();
        String userNameRe = SpecialCodeReplaceUtil.doReplace(userName);

        try {
            StudentInfo studentInfo = studentMapper.studentLoginCheck(userNameRe);
            if(studentInfo == null){
                replyMessage.setStatus(400);
                replyMessage.setInfo("用户不存在，请检查用户名！");
                return replyMessage;
            }

            int adminLock = studentInfo.getAdminLock();
            if(adminLock != 0){
                replyMessage.setStatus(400);
                replyMessage.setInfo("账号已被限制登录，请联系客服了解详情");
                return replyMessage;
            }

            int sysLock = studentInfo.getSysLock();
            if(sysLock != 0){
                replyMessage.setStatus(400);
                replyMessage.setInfo("今天之内密码错误次数太多，为保护账号安全，账号已被锁定，请在24小时后重试或联系客服解决");
                return replyMessage;
            }

            String passwordEn = Md5Utils.getMd5(password);
            if(studentInfo.getPassword().equals(passwordEn)){
                studentInfo.setPassword("");
                studentInfo.setName(userName);
                replyMessage.setStatus(200);
                replyMessage.setObject(studentInfo);
                return replyMessage;
            }

            // 账号锁定
            int dayError = studentInfo.getErrorTime();
            int studentId = studentInfo.getId();
            if(dayError > 10){
                studentMapper.sysLockStudent(studentId);
                studentMapper.sysAutoUnLock(studentId);
            }
            studentMapper.updateDayError(studentId);

            replyMessage.setStatus(400);
            replyMessage.setInfo("密码错误！");
            return replyMessage;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("学生登录时异常，学生登录名："+userName+"，登录密码："+password);

            replyMessage.setStatus(500);
            replyMessage.setInfo("服务器异常，请稍后重试！");
            return replyMessage;
        }
    }

    /**
     * 学生修改基本信息
     */
    public ReplyMessage updateBaseInfo(StudentInfo studentInfo){
        // 真实姓名
        String realName = SpecialCodeReplaceUtil.doReplace(studentInfo.getRealName());
        studentInfo.setRealName(realName);

        // 学校
        String school = SpecialCodeReplaceUtil.doReplace(studentInfo.getSchool());
        studentInfo.setSchool(school);

        // 性别
        if (studentInfo.getSex() == 1) {
            studentInfo.setSex(1);
        } else {
            studentInfo.setSex(0);
        }

        ReplyMessage replyMessage = new ReplyMessage();
        try {
            studentMapper.updateStudentBaseInfo(studentInfo);

            replyMessage.setStatus(200);
            return replyMessage;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("修改学生基础信息异常，学生ID："+studentInfo.getId());

            replyMessage.setStatus(500);
            replyMessage.setInfo("服务器异常，请稍后重试！");
            return replyMessage;
        }
    }

    /**
     * 修改学生登录名
     */
    public ReplyMessage updateStudentLoginName(StudentInfo studentInfo){
        String loginName = SpecialCodeReplaceUtil.doReplace(studentInfo.getName());
        studentInfo.setName(loginName);

        ReplyMessage replyMessage = new ReplyMessage();
        try {
            studentMapper.updateStudentLoginName(studentInfo);
            replyMessage.setStatus(200);
            return replyMessage;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("修改学生登录名异常，学生ID："+studentInfo.getId());

            replyMessage.setStatus(500);
            replyMessage.setInfo("服务器异常，请稍后重试！");
            return replyMessage;
        }
    }

    /**
     * 修改学生密码
     */
    public ReplyMessage updateStudentPassword(String oldPassword, String newPassword, int id){
        ReplyMessage replyMessage = new ReplyMessage();

        try {
            String queryPassword = studentMapper.queryStudentPassword(id);
            if(queryPassword != null){
                String oldPasswordEn = Md5Utils.getMd5(oldPassword);
                if(queryPassword.equals(oldPasswordEn)){
                    String newPasswordEn = Md5Utils.getMd5(newPassword);
                    studentMapper.updateStudentPassword(id, newPasswordEn);

                    replyMessage.setStatus(200);
                    return replyMessage;
                }
                replyMessage.setStatus(400);
                replyMessage.setInfo("原密码不正确！");
                return replyMessage;
            }
            replyMessage.setStatus(400);
            replyMessage.setInfo("修改密码失败，服务器出现错误，请重新登录后尝试修改！");
            return replyMessage;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("修改学生密码异常，学生ID："+id);

            replyMessage.setStatus(500);
            replyMessage.setInfo("服务器异常，请稍后重试！");
            return replyMessage;
        }
    }

    /**
     * 修改学生手机号
     */
    public ReplyMessage updateStudentPhone(StudentInfo studentInfo){
        ReplyMessage replyMessage = new ReplyMessage();
        try {
            studentMapper.updateStudentPhone(studentInfo);
            replyMessage.setStatus(200);
            return replyMessage;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("修改学生手机号异常，学生ID："+studentInfo.getId());

            replyMessage.setStatus(500);
            replyMessage.setInfo("服务器异常，请稍后重试！");
            return replyMessage;
        }
    }

    /**
     * 修改学生QQ号和微信号
     */
    public ReplyMessage updateStudentConnect(StudentInfo studentInfo){
        ReplyMessage replyMessage = new ReplyMessage();
        try {
            studentMapper.updateStudentConnect(studentInfo);
            replyMessage.setStatus(200);
            return replyMessage;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("修改学生联系信息异常，学生ID："+studentInfo.getId());

            replyMessage.setStatus(500);
            replyMessage.setInfo("服务器异常，请稍后重试！");
            return replyMessage;
        }
    }

    /**
     * 查找用户是否存在该手机号
     */
    public StudentInfo queryPhoneByName(String loginName,String phoneNum){
        String loginNameRe = SpecialCodeReplaceUtil.doReplace(loginName);
        try {
            StudentInfo studentInfo =  studentMapper.queryStudentPhone(loginNameRe);
            if(studentInfo != null){
                if(studentInfo.getPhone().equals(phoneNum)){
                    return studentInfo;
                }
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("根据学生登录名称查询学生手机号异常，学生登录名："+loginName);

            return null;
        }
    }

    /**
     * 查询学生当天课程信息
     */
    public ReplyMessage queryStudentCurrentClassInfo(int studentId){
        ReplyMessage replyMessage = new ReplyMessage();

        try {
            List<ClassInfoManager> classInfoManagerList = studentMapper.queryCurrentClassInfo(studentId);
            if(classInfoManagerList != null){
                replyMessage.setStatus(200);
                replyMessage.setInfo(JSON.toJSONString(classInfoManagerList));
                return replyMessage;
            }
            replyMessage.setStatus(400);
            replyMessage.setInfo("查询结果为空！");
            return replyMessage;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("学生查询课程信息异常，学生ID："+studentId);

            replyMessage.setStatus(500);
            replyMessage.setInfo("服务器异常，请稍后重试！");
            return replyMessage;
        }
    }
}
